<script setup lang="ts">
import type { AddSignRequest } from '@/api/types/workflow'
import { onLoad } from '@dcloudio/uni-app'
import { definePage } from '@uni-helper/vite-plugin-uni-pages'
import { reactive, ref } from 'vue'
import { addSignTask } from '@/api/workflow'
import SelectedUsers from '@/components/SelectedUsers.vue'
import ApprovalActionFooter from './components/ApprovalActionFooter.vue'
import ApprovalOpinion from './components/ApprovalOpinion.vue'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '审批加签',
    navigationBarTextStyle: 'black',
  },
})

// 页面参数
const params = ref<{ id?: string, title?: string }>({})

// 表单数据
const formData = reactive({
  selectedUsers: [] as string[], // 支持多选
  comment: '', // 加签说明
  addSignType: 'after' as 'after' | 'before' | 'parallel' | 'serial', // parallel: 会签, serial: 或签
})

// 加载状态
const loading = ref(false)

// 监听页面加载，获取参数
onLoad((options) => {
  params.value = options
  console.log(params.value)
  // 如果有title参数，设置导航栏标题
  if (options.title) {
    uni.setNavigationBarTitle({
      title: `${decodeURIComponent(options.title as string)}-加签`,
    })
  }
})

// 加签操作函数
async function handleAddSign() {
  if (formData.selectedUsers.length === 0) {
    uni.showToast({
      title: '请至少选择一位加签人员',
      icon: 'none',
    })
    return
  }

  try {
    loading.value = true

    // 构造请求参数
    const requestData: AddSignRequest = {
      id: params.value.id || '',
      userIds: formData.selectedUsers,
      reason: formData.comment || '',
      type: formData.addSignType || 'after',
    }

    console.log('加签审批操作', requestData)
    // 调用审批加签API
    const res = await addSignTask(requestData)

    if (res.data) {
      uni.showToast({
        title: '加签成功',
        icon: 'success',
      })
      setTimeout(() => {
        // 如果是向前加签，跳转到待办列表，如果是向后加签，返回详情
        if (formData.addSignType === 'before') {
          uni.switchTab({
            url: '/pages/list/todo',
          })
        }
        else {
          uni.navigateBack()
        }
      }, 1500)
    }
    else {
      uni.showToast({
        title: res.data?.message || '加签失败，请重试',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('加签审批失败:', error)
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <view class="approval-container min-h-screen bg-gray-100">
    <!-- 加签类型选择（移到最顶部） -->
    <view class="sign-type-section mb-2">
      <text class="sign-type-title">加签类型</text>
      <view class="sign-type-options">
        <view
          class="sign-type-item"
          :class="{ 'sign-type-item-active': formData.addSignType === 'before' }"
          @click="formData.addSignType = 'before'"
        >
          <text class="sign-type-item-title" :class="{ 'sign-type-item-title-active': formData.addSignType === 'before' }">向前加签</text>
          <text class="sign-type-item-desc">向加签人之前加签</text>
        </view>
        <view
          class="sign-type-item"
          :class="{ 'sign-type-item-active': formData.addSignType === 'after' }"
          @click="formData.addSignType = 'after'"
        >
          <text class="sign-type-item-title" :class="{ 'sign-type-item-title-active': formData.addSignType === 'after' }">向后加签</text>
          <text class="sign-type-item-desc">向加签人之后加签</text>
        </view>
      </view>
    </view>
    <!-- 加签说明 -->
    <ApprovalOpinion
      v-model="formData.comment"
      placeholder="请输入加签说明"
      :required="false"
      title="加签说明"
    />

    <!-- 已选人员 -->
    <SelectedUsers v-model="formData.selectedUsers" title="选择加签人员" :required="true" />

    <ApprovalActionFooter
      :loading="loading"
      :disabled="formData.selectedUsers.length === 0"
      @confirm="handleAddSign"
    />
  </view>
</template>

<style scoped>
.sign-type-section {
  margin-top: 8px;
  background-color: #ffffff;
  padding: 20px;
}

.sign-type-title {
  margin-bottom: 12px;
  display: block;
  font-size: 16px;
  font-weight: 500;
}

.sign-type-options {
  display: flex;
  gap: 16px;
}

.sign-type-item {
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px solid #dbeafe;
  border-radius: 8px;
  background-color: #eff6ff;
  padding: 16px;
  transition: all 0.3s;
}

.sign-type-item-active {
  border-width: 2px;
  border-color: #22c55e;
  background-color: #dcfce7;
  box-shadow: 0 2px 8px rgba(34, 197, 94, 0.2);
}

.sign-type-item-title {
  margin-bottom: 4px;
  font-size: 16px;
  font-weight: 500;
}

.sign-type-item-title-active {
  color: #16a34a;
  font-weight: bold;
}

.sign-type-item-desc {
  text-align: center;
  font-size: 12px;
  color: #6b7280;
}

.user-picker-overlay {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
